package com.seth.myapplication;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.seth.myapplication.bean.User;
import com.seth.myapplication.service.NetWorkService;
import com.seth.myapplication.surface.page4Fragment;
import com.seth.myapplication.utils.SqlDao;

/**
 * Created by Seth on 2017/12/6.
 */

public class LaunchActivity extends AppCompatActivity {
    public static final String LAUNCH_RECEIVER = "com.seth.myapplication.LaunchActivity" ;
    private DataApp mDataApp;
    private User mUser;
    private MsgReceiver msgReceiver;
    private Boolean flagLogin = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launch);
        mDataApp = (DataApp) getApplication();
        mUser = new SqlDao(this).usrQuery();
        //动态注册广播接收器
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LAUNCH_RECEIVER);
        registerReceiver(msgReceiver, intentFilter);

        if(mUser!=null) {
            new NetWorkService(LaunchActivity.this, LAUNCH_RECEIVER).usrLogin(mUser);

            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (!flagLogin) {
                        mDataApp.setUser(null);
                        int rs = new SqlDao(LaunchActivity.this).delUsr();
                        Log.i("SQLiteresult", rs + "");
                    } else {
                        mDataApp.setUser(mUser);
                    }
                    startActivity(new Intent(getApplication(), MainActivity.class));
                }
            }, 3000);
        }else{
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mDataApp.setUser(null);
                    startActivity(new Intent(getApplication(), MainActivity.class));
                }
            },1000);
        }
    }

    /**
     * 广播接收器
     * @author len
     *
     */
    public class MsgReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            //拿到进度，更新UI
            int result = intent.getIntExtra("result", 0);
            if(result==1){
                flagLogin=true;
            }else if(result==2){
                flagLogin=false;
                Toast.makeText(context, "密码错误", Toast.LENGTH_SHORT).show();
            }else if(result==3){
                flagLogin=false;
                Toast.makeText(context, "账号不存在", Toast.LENGTH_SHORT).show();
            }
        }

    }
}
